package com.alibaba.shopping_pay_service.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.shopping_common.pojo.Orders;
import com.alibaba.shopping_common.pojo.Payment;
import com.alibaba.shopping_common.result.BusException;
import com.alibaba.shopping_common.service.AlipayService;
import com.alibaba.shopping_pay_service.ZfbPayConfig;
import com.alibaba.shopping_pay_service.mapper.PaymentMapper;
import com.alibaba.shopping_pay_service.util.ZfbVerifierUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

import static com.alibaba.shopping_common.result.CodeEnum.CHECK_SIGN_ERROR;
import static com.alibaba.shopping_common.result.CodeEnum.QR_CODE_ERROR;

/**
 * @ClassName AlipayServiceImpl
 * @Description 支付宝服务实现类
 * @Author Leo
 * @Date 2024/12/19 14:05
 */
@DubboService
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private ZfbPayConfig zfbPayConfig;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public String pcPay(Orders orders) {
        // 1.创建请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(zfbPayConfig.getNotifyUrl()+zfbPayConfig.getPcNotify());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",orders.getId());
        bizContent.put("total_amount",orders.getPayment());
        bizContent.put("subject",orders.getCartGoods().get(0).getGoodsName());
        request.setBizContent(bizContent.toJSONString());

        try {
            // 发送请求
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            System.out.println("返回二维码:"+response);
            // 返回二维码
            return response.getQrCode();
        } catch (AlipayApiException e) {
            throw new BusException(QR_CODE_ERROR);
        }
    }

    @Override
    public void checkSign(Map<String, Object> paramMap) {
        // 获取所有的参数
        Map<String,String[]> requestParamterMap = (Map<String, String[]>) paramMap.get("requestParameter");
        // 验签
        boolean valid = ZfbVerifierUtils.isValid(requestParamterMap, zfbPayConfig.getPublicKey());
        // 验签失败，抛出异常
        if (!valid){
            throw new BusException(CHECK_SIGN_ERROR);
        }

    }

    // 存储交易记录方法
    @Override
    public void addPayment(Payment payment) {
        paymentMapper.insert(payment);
    }
}




